//
//  NewOrEitdViewController.m
//  jingdongfang
//
//  Created by 郝志宇 on 16/8/9.
//  Copyright © 2016年 ZhiYu Hao. All rights reserved.
//

#import "NewOrEitdViewController.h"
#import "TPKeyboardAvoidingTableView.h"
#import "AreaViewController.h"
#import "AddressViewController.h"
#import "IGAddAddressApi.h"
#import "IGUpDateAddressApi.h"
#import "RegionListModel.h"
#import "CityListModel.h"
#import "CountryListModel.h"


@interface NewOrEitdViewController () <UITableViewDelegate, UITableViewDataSource> {
    NSString *name;
    NSString *number;
    NSString *area;
    NSString *address;
    NSString *addresssId;
    
    NSString *city;
    
    RegionListModel *regionlist;
    CityListModel *citylist;
    CountryListModel *coutrylist;
}

@property (weak, nonatomic) IBOutlet TPKeyboardAvoidingTableView *table;
@property (nonatomic, strong) IGAddAddressApi *addAddressApi;
@property(nonatomic,strong)IGUpDateAddressApi *upDateAddressApi;
@end

@implementation NewOrEitdViewController
#pragma mark -生命周期
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
//    self.title = @"新建地址";
    self.title = NSLocalizedString(@"New Address", nil);
    if (self.isEdit) {
//        self.title = @"编辑地址";
        self.title = NSLocalizedString(@"Edit Your Address", nil);
    }
    self.table.backgroundColor=[UIColor c2Color];
    if (@available(iOS 11.0, *)) {
        self.table.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        self.table.contentInset = UIEdgeInsetsMake(64, 0, 49, 0);
        self.table.scrollIndicatorInsets = self.table.contentInset;
    }
//    [self ig_setupRightButtonItemWithTitle:@"确定" image:nil highLightedImage:nil];
    [self ig_setupRightButtonItemWithTitle:NSLocalizedString(@"Confirm", nil) image:nil highLightedImage:nil];
    
    self.navigationController.navigationBar.tintColor = [UIColor grayColor];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemStop target:self action:@selector(cancelAction:)];
}

- (void)setAddressItem:(IGAddressItem *)addressItem {
    _addressItem = addressItem;

    name = addressItem.name;
    number = addressItem.tel;
    addresssId = addressItem.aid;
    area = addressItem.addressNm;
    address = addressItem.detail;
    city = addressItem.addressId;
}

#pragma mark - UITableViewDelegate, UITableViewDataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 4;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:nil];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    UIColor *color = [UIColor lightGrayColor];
    
    CGFloat h = [self tableView:tableView heightForRowAtIndexPath:indexPath];
    
    UITextField *textView = [[UITextField alloc] initWithFrame:CGRectMake(25, 0, KSCREENWIDTH-50, h)];
    textView.borderStyle = UITextBorderStyleNone;
    textView.font = [UIFont systemFontOfSize:15];
    textView.clearButtonMode = UITextFieldViewModeWhileEditing;
    textView.leftViewMode = UITextFieldViewModeAlways;
    [textView addTarget:self action:@selector(textChange:) forControlEvents:UIControlEventEditingChanged];
    textView.tag = indexPath.row;
    
    UILabel *msg = [[UILabel alloc] initWithFrame:CGRectZero];
    msg.font = textView.font;
//    msg.text = @"占位字符";
    msg.text = NSLocalizedString(@"Spacing Character", nil);
    [msg sizeToFit];
    msg.width += 20;

    if (indexPath.row==0) {
//        msg.text = @"收货人";
        msg.text = NSLocalizedString(@"Recipient", nil);
        textView.leftView = msg;
//        textView.placeholder = @"请输入收货人";
        textView.placeholder = NSLocalizedString(@"Recipient", nil);
        textView.text = name;
        textView.keyboardType = UIKeyboardTypeDefault;
        [cell.contentView addSubview:textView];
    } else if (indexPath.row==1) {
//        msg.text = @"手机号码";
        msg.text = NSLocalizedString(@"Mobile Number", nil);

        textView.leftView = msg;
//        textView.placeholder = @"请输入手机号";
        textView.placeholder = NSLocalizedString(@"Mobile Number", nil);
        textView.text = number;
        textView.keyboardType = UIKeyboardTypePhonePad;
        [cell.contentView addSubview:textView];
    } else if (indexPath.row==2) {
//        msg.text = @"所在地区";
        msg.text = NSLocalizedString(@"Location", nil);

        textView.leftView = msg;
//        textView.placeholder = @"请选择所在地区";
        textView.placeholder = NSLocalizedString(@"Location", nil);
        textView.text = area;
        textView.keyboardType = UIKeyboardTypeDefault;
        textView.enabled = NO;
        [cell.contentView addSubview:textView];
    } else if (indexPath.row==3) {
//        msg.text = @"详细地址";
        msg.text = NSLocalizedString(@"Detailed Address", nil);

        textView.leftView = msg;
//        textView.placeholder = @"请填写详细地址";
        textView.placeholder = NSLocalizedString(@"Detailed Address", nil);
        textView.text = address;
        textView.keyboardType = UIKeyboardTypeDefault;
        [cell.contentView addSubview:textView];
        
        color = [UIColor appColor];
    }
    
    UILabel *line = [[UILabel alloc] initWithFrame:CGRectMake(15, h-0.5, KSCREENWIDTH-30, .5)];
    line.backgroundColor = color;
    [cell.contentView addSubview:line];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row==2) {
        AreaViewController *vc = [[AreaViewController alloc] init];
        BaseNavigationController *nav = [[BaseNavigationController alloc] initWithRootViewController:vc];
        [vc selAreaSucc:^(RegionListModel *selProvi, CityListModel *selCity, CountryListModel *selArea) {
            NSMutableArray *arr1 = [NSMutableArray array];
            [arr1 addObject:selProvi.provinceName];
            [arr1 addObject:selCity.cName];
            [arr1 addObject:selArea.countryName];
            
            NSMutableArray *arr2 = [NSMutableArray array];
            [arr2 addObject:selProvi.provinceId];
            [arr2 addObject:selCity.cityId];
            [arr2 addObject:selArea.countryId];
            
            area = [arr1 componentsJoinedByString:@"-"];
            city = [arr2 componentsJoinedByString:@"-"];
            [self.table reloadData];
    }];
        [self.navigationController presentViewController:nav animated:YES completion:NULL];
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 50;
}
#pragma mark -编辑textfield
- (void)textChange:(UITextField *)textView {
    if (textView.tag == 0) {
        UITextRange *markedRange = [textView markedTextRange];
        if (markedRange) {
            return;
        }
        if (textView.text.length > 10) {
            NSRange range = [textView.text rangeOfComposedCharacterSequenceAtIndex:10];
            //            [self presentMessageTips:@"名字长度不能大于10"];
            [self presentMessageTips:NSLocalizedString(@"Name Length ≤10 Words", nil)];
            textView.text = [textView.text substringToIndex:range.location];
        }
        name = textView.text;
    } else if (textView.tag == 1) {
        //手机号
        if (textView.text.length>11) {
            textView.text = [textView.text substringToIndex:11];
        }
        number = textView.text;
    } else if (textView.tag == 3) {
        
        address = textView.text;
    }
}

- (void)cancelAction:(UIBarButtonItem *)btn {
    [self.view endEditing:YES];
    [self.navigationController dismissViewControllerAnimated:YES completion:NULL];
}

- (void)ig_rightButtonPressed:(id)sender {
    [self.view endEditing:YES];
    
    if (name.length==0) {
//        [self presentMessageTips:@"请输入收货人"];
        [self presentMessageTips:NSLocalizedString(@"Please Input Recipient", nil)];
        return;
    }
    if (number.length==0) {
//        [self presentMessageTips:@"请输入手机号"];
        [self presentMessageTips:NSLocalizedString(@"Please Input Mobile Number", nil)];
        return;
    }
    if (![number isTelephone]) {
//        [self presentMessageTips:@"请输入正确的手机号"];
        [self presentMessageTips:NSLocalizedString(@"Please Input Correct Mobile No.", nil)];
        return;
    }
    if (area.length==0) {
//        [self presentMessageTips:@"请选择所在地区"];
        [self presentMessageTips:NSLocalizedString(@"Please Select Location", nil)];

        return;
    }
    if (address.length==0) {
//        [self presentMessageTips:@"请填写详细地址"];
        [self presentMessageTips:NSLocalizedString(@"Please provide full address", nil)];

        return;
    }
    __weak typeof(self) weakSelf = self;
    if ([self isEdit]) {
        self.upDateAddressApi=[[IGUpDateAddressApi alloc] initWithConsignee:name phone:number region:city detail:address addressId:addresssId];
        [self.upDateAddressApi startWithDecodeClass:[IGUpDateAddressResp class] CompletionBlockWithSuccess:^(id responseObject, NSError *error) {
            if (responseObject) {
                [weakSelf.navigationController dismissViewControllerAnimated:YES completion:nil];
            }
        }];
    }else{
        self.addAddressApi=[[IGAddAddressApi alloc] initWithConsignee:name phone:number region:city detail:address];
        [self.addAddressApi startWithDecodeClass:[IGAddAddressResp class] CompletionBlockWithSuccess:^(id responseObject, NSError *error) {
            if (responseObject) {
                [weakSelf.navigationController dismissViewControllerAnimated:YES completion:NULL];
            }
        }];
    }
   
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
